package com.mybatis.jpa.statement.builder;

import java.lang.reflect.Method;

import javax.persistence.OrderBy;

import org.apache.ibatis.executor.keygen.NoKeyGenerator;
import org.apache.ibatis.mapping.SqlCommandType;

import com.mybatis.jpa.constant.ResultMapConstants;
import com.mybatis.jpa.meta.PersistentMeta;
import com.mybatis.jpa.statement.MybatisStatementAdapter;
import com.mybatis.jpa.statement.SqlAssistant;

/**
 * 带分页的
 * @author jackwong
 *
 */
public class SelectPageBuilder implements StatementBuildable {

	@Override
	public String buildSQL(PersistentMeta persistentMeta, Method method) {
		StringBuilder resultSql =  new StringBuilder("<script> SELECT " + persistentMeta.getColumnNames() + " FROM ");
        if(persistentMeta.isCatTable())
        {
            resultSql.append(persistentMeta.getTableName() + "_${entity." + persistentMeta.getFlat() + "}");
        }
        else
        {
            resultSql.append(persistentMeta.getTableName());
        }

		resultSql.append(SqlAssistant.builderModelWhere(persistentMeta, "entity.",false));
		resultSql.append(this.extWhere() + "</where>");
		return resultSql.toString();
	}

	@Override
	public void parseStatement(MybatisStatementAdapter adapter, PersistentMeta persistentMeta, Method method) {
		// 方法名
		adapter.setMethodName(method.getName());
		// 参数类型
		if (method.getParameterTypes().length > 0) {
			// Mybatis mapper 方法最多支持一个参数,先设置成Object.class,mybatis会在sql中解析
			adapter.setParameterTypeClass(Object.class);
		} else {
			adapter.setParameterTypeClass(void.class);
		}

		String orderBy = getOrderByInfo( adapter,  persistentMeta,  method);


		String limit = "  ";
		limit = " <if test=\"pageStart != -1 and pageSize !=-1 \" >  " +
				"        LIMIT  ${pageStart},${pageSize} " +
				"      </if> </script>";

		// sqlScript
		adapter.setSqlScript(buildSQL(persistentMeta, method) + orderBy + limit);
		// 返回值类型
		adapter.setResultType(persistentMeta.getType());
		adapter.setResultMapId(ResultMapConstants.DEFAULT_NAMESPACE + "." + persistentMeta.getEntityName());

		adapter.setSqlCommandType(SqlCommandType.SELECT);

		// 主键策略
		adapter.setKeyGenerator(new NoKeyGenerator());
		adapter.setKeyProperty(null);
		adapter.setKeyColumn(null);

		adapter.parseStatement();

	}

	/**
	 * 扩展where 条件
	 * @return  扩展where条件
	 */
	public String extWhere(){
		return "";
	}

	/**
	 * 获取order by的info
	 * @param adapter
	 * @param persistentMeta
	 * @param method
	 * @return
	 */
	public String getOrderByInfo(MybatisStatementAdapter adapter, PersistentMeta persistentMeta, Method method){

		if (method.isAnnotationPresent(OrderBy.class)) {
		      return " ORDER BY " + method.getAnnotation(OrderBy.class).value();
		}else if (adapter.getOrderBy() != null && !"".equals(adapter.getOrderBy())) {
			   return  " ORDER BY " + adapter.getOrderBy();
		}
		return "";
	}
}
